#include "common.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        CliErr();
        exit(ERR_CLI);
    }
    // 1.获得IP
    std::string lo_ip(argv[1]);
    uint16_t lo_port = std::stoi(argv[2]);
    // 2.获得sockfd
    int lo_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lo_sockfd < 0)
    {
        Local_Log::LOG(Local_Log::LogLever::LFATAL) << "socket error";
        exit(ERR_SOCKET);
    }
    // 3.连接
    Local_Inetaddr::Inetaddr lo_clientaddr(lo_ip, lo_port);
    int con_ret = connect(lo_sockfd, lo_clientaddr.GetAddrPtr(), lo_clientaddr.GetAddrSize());
    if (con_ret < 0)
    {
        Local_Log::LOG(Local_Log::LogLever::LFATAL) << "connect error";
        perror("-->>");
        exit(ERR_CONNECT);
    }

    char lo_werbuffer[64];
    char lo_reabuffer[64];

    while (1)
    {
        // 4.发送
        memset(lo_werbuffer, 0, sizeof(lo_werbuffer));
        std::cin>>lo_werbuffer;
        int wri_ret = write(lo_sockfd, lo_werbuffer, sizeof(lo_werbuffer) - 1);
        if (wri_ret == -1)
        {
            Local_Log::LOG(Local_Log::LogLever::LWARNING) << "write error";
            continue;
        }
        // 5.接收
        memset(lo_reabuffer, 0, sizeof(lo_reabuffer));
        int rea_ret = read(lo_sockfd, lo_reabuffer, sizeof(lo_reabuffer) - 1);
        if (rea_ret <= 0)
        {
            Local_Log::LOG(Local_Log::LogLever::LWARNING) << "read error";
            continue;
        }
        std::cout << "-->> " << lo_reabuffer << std::endl;
    }

    return 0;
}